package com.itheima.auth;

import com.itheima.cst.SysConsts;
import com.itheima.dto.UserDTO;
import com.itheima.pojo.MyUser;
import com.itheima.utils.RedisUtil;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 用户登入要找它
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    //从数据库查数据
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserDTO user= RedisUtil.get(SysConsts.REDIS_USER_PREFIX+username);
        if (user!=null){
            //执行到此，则代表有数据
            List<String> list = user.getAuthority();
            String[] authorises = new String[list.size()];
            return new User(username,user.getPassword(), AuthorityUtils.createAuthorityList(list.toArray(authorises)));

        }
        return null;
    }
}
